package com.czk.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czk.common.utils.PageUtils;
import com.czk.common.utils.Query;
import com.czk.gulimall.product.dao.BrandDao;
import com.czk.gulimall.product.entity.BrandEntity;
import com.czk.gulimall.product.service.BrandService;
import com.czk.gulimall.product.service.CategoryBrandRelationService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {
    @Resource
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        // 拿到搜索条件
        String key = (String) params.get("key");
        QueryWrapper<BrandEntity> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(key)) {
            // 根据id或品牌名模糊查询
            wrapper.eq("brand_id", key).or().like("name", key);
        }
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void updateDetail(BrandEntity brand) {
        // 保证冗余字段的数据一致
        this.updateById(brand);
        // 修改关联的冗余字段
        if (!StringUtils.isEmpty(brand.getName())) {
            // 同步更新其他关联表的数据
            // todo 有事务问题
            categoryBrandRelationService.updateBrand(brand.getBrandId(),brand.getName());
        }
    }

    @Override
    public List<BrandEntity> getBrandByIds(List<Long> brandIds) {
        List<BrandEntity> brandEntities = this.baseMapper.selectList(new QueryWrapper<BrandEntity>().in("brand_id",brandIds));
        return brandEntities;
    }
}